package work.flow.demo.api;


import org.apache.juli.logging.Log;
import org.flowable.engine.*;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Comment;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import work.flow.demo.config.constant.ProcessConfig;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ProcessTest04 {
    private static final Logger logger = LoggerFactory.getLogger(ProcessTest04.class);

    @Qualifier("ProcessConfig")
    private final ProcessEngine processEngine;


    public ProcessTest04(ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    //添加请假发起人
    @GetMapping("/p4_01")
    public String get01(@RequestParam Map<String, String> params) {
        //参数-发起人
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }

        IdentityService identityService = processEngine.getIdentityService();

        // 1、创建用户组,user_g和bpmn文件中的组对应（通常在bpmn文件已经创建）
        Group existingGroup = identityService.createGroupQuery().groupId("user_g").singleResult();
        if (existingGroup == null) {
            Group starterGroup = identityService.newGroup("user_g");
            starterGroup.setName("请假发起人组");
            starterGroup.setType("starter");
            identityService.saveGroup(starterGroup);
        }

        // 2、检查用户是否在授权组中
        boolean isAuthorized = identityService.createGroupQuery()//
                .groupMember(userId)//
                .groupId("user_g")//
                .count() > 0;//

        if (isAuthorized) {
            return "该用户已经授权发起请假流程，请不要重复添加";
        } else {
            //创建用户
            User newUser = identityService.newUser(userId);
            newUser.setFirstName("Han");  // 可选：设置用户信息
            newUser.setLastName("Meimei");
            newUser.setEmail("hm@example.com");
            identityService.saveUser(newUser);
            // 将用户加入组
            identityService.createMembership(userId, "user_g");
            return "用户已经授权发起请假流程-" + userId;
        }
    }

    //添加请假处理人-班主任
    @GetMapping("/p4_02")
    public String get02(@RequestParam Map<String, String> params) {
        //参数-发起人
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }

        IdentityService identityService = processEngine.getIdentityService();

        // 1、创建用户组,user_g和bpmn文件中的组对应（通常在bpmn文件已经创建）
        Group existingGroup = identityService.createGroupQuery().groupId("teacher_g").singleResult();
        if (existingGroup == null) {
            Group starterGroup = identityService.newGroup("teacher_g");
            starterGroup.setName("请假处理人组");
            starterGroup.setType("handle");
            identityService.saveGroup(starterGroup);
        }

        //全局查询（同一个id不能重复添加组）
        //User user = identityService.createUserQuery().userId("hm").singleResult();

        // 2、检查用户是否在授权组中
        boolean isAuthorized = identityService.createGroupQuery()//
                .groupMember(userId)//
                .groupId("teacher_g")//
                .count() > 0;//

        if (isAuthorized) {
            return "该用户已经授权班主任组，请不要重复添加";
        } else {
            //创建用户
            User newUser = identityService.newUser(userId);
            newUser.setFirstName("teacher");  // 可选：设置用户信息
            newUser.setLastName("teacher");
            newUser.setEmail("hm@example.com");
            identityService.saveUser(newUser);
            // 将用户加入组
            identityService.createMembership(userId, "teacher_g");
            return "该用户已经授权班主任组-" + userId;
        }
    }

    //发起请假流程，班主任处理
    @GetMapping("/p4_03")
    public String get03(@RequestParam Map<String, String> params) {
        //参数-发起人
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }

        // 1、检查用户是否在授权组中
        IdentityService identityService = processEngine.getIdentityService();
        boolean isAuthorized = identityService.createGroupQuery()//
                .groupMember(userId)//
                .groupId("user_g")//
                .count() > 0;//
        if (!isAuthorized) {
            return "该用户没有授权请假流程";
        }

        //2、获取流程实例
        RuntimeService runtimeService = processEngine.getRuntimeService();

        //3、发起流程,businessK业务id不可变
        String processId = "test_04";//对应bpmn文件中的test_04
        Map<String, Object> variables = new HashMap<>();
        variables.put("initiator", userId);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processId, "businessKey", variables);
        TaskService taskService = processEngine.getTaskService();
        //查询该用户当前的任务
        List<Task> tasks = taskService.createTaskQuery()//
                .taskCandidateUser(userId)//根据用户id查询任务
                .list();
        if (!tasks.isEmpty()) {
            for (Task task : tasks) {
                System.out.println("需先完成任务: " + task.getName());
                taskService.complete(task.getId());  // 完成任务，流转到班主任任务
            }
        }
        return "用户：" + userId + "请假成功" + processInstance.getId();
    }

    //查询某个组的所有用户
    @GetMapping("/p4_99")
    public String get99(@RequestParam Map<String, String> params) {
        //参数
        String groupId = params.get("groupId");

        // 查询组内用户列表
        IdentityService identityService = processEngine.getIdentityService();
        List<User> users = identityService.createUserQuery()//
                .memberOfGroup(groupId) // 属于 teacher_g 的用户
                .list();
        // 遍历用户
        StringBuilder resp = new StringBuilder();
        for (User user : users) {
            resp.append("用户ID: ").append(user.getId()).append(", 姓名: ").append(user.getFirstName()).append(" ").append(user.getLastName());
        }

        return resp.toString();
    }


    //请假流程处理，班主任处理
    @GetMapping("/p4_04")
    public String get04(@RequestParam Map<String, String> params) {
        //参数
        String userId = params.get("userId");

        if (userId == null || userId.isEmpty()) {
            return "请输入用户ID";
        }

        // 2、检查用户是否在授权组中
        IdentityService identityService = processEngine.getIdentityService();
        boolean isAuthorized = identityService.createGroupQuery()//
                .groupMember(userId)//
                .groupId("teacher_g")//
                .count() > 0;//

        if (!isAuthorized) {
            return "该班主任不在授权组中";
        }

        // 查询并处理流程
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery()//
                .taskCandidateUser(userId)//根据用户id查询任务
                .list();

        if (!tasks.isEmpty()) {
            for (Task task : tasks) {
                taskService.complete(task.getId());  // 完成任务，流转到班主任任务
            }
        }

        return "班主任共有：" + tasks.size() + "条任务要处理";

    }

    //查询已完成的任务
    @GetMapping("/p4_05")
    public String get05(@RequestParam Map<String, String> params) {
        HistoryService historyService = processEngine.getHistoryService();

        // 查询所有已完成的任务
        List<HistoricTaskInstance> completedTasks = historyService.createHistoricTaskInstanceQuery()//
                .finished()  // 只查询已完成的任务
                .list();

        // 遍历输出
        for (HistoricTaskInstance task : completedTasks) {
            System.out.println("任务ID: " + task.getId());
            System.out.println("任务名称: " + task.getName());
            System.out.println("流程实例ID: " + task.getProcessInstanceId());
            System.out.println("完成时间: " + task.getEndTime());
            System.out.println("----------------------");
        }

        return "共有：" + completedTasks.size() + "已完成";

    }

    //删除已完成的流程实例
    @GetMapping("/p4_06")
    public String get06(@RequestParam Map<String, String> params) {
        HistoryService historyService = processEngine.getHistoryService();
        ManagementService managementService = processEngine.getManagementService();

        // 删除已完成的流程实例（保留最近30天的）
        historyService.createHistoricProcessInstanceQuery().finished()  // 只查询已完成的流程
                //.finishedBefore(new Date(System.currentTimeMillis() - 30L * 24 * 60 * 60 * 1000)) // 30天前
                .list().forEach(instance -> {
                    historyService.deleteHistoricProcessInstance(instance.getId()); // 删除历史流程
                });

        // 删除关联的历史任务、变量等
        //managementService.executeCommand(new DeleteHistoryProcessInstancesCmd());

        return "删除成功";

    }

    //删除单个流程实例
    @GetMapping("/p4_07")
    public String get07(@RequestParam Map<String, String> params) {
        //参数
        String processInstanceId = params.get("processInstanceId");

        if (processInstanceId == null || processInstanceId.isEmpty()) {
            return "请输入processInstanceId";
        }
        HistoryService historyService = processEngine.getHistoryService();
        historyService.deleteHistoricProcessInstance(processInstanceId); // 删除历史流程

        return "删除成功";

    }

    //查询审批意见-处理记录
    @GetMapping("/p4_08")
    public String get08(@RequestParam Map<String, String> params) {
        // 通过 businessKey 查询流程实例
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey("businessKey")  // 替换为你的 businessKey
                .singleResult();

        if (instance != null) {
            System.out.println("流程状态: 运行中");
            System.out.println("0当前节点: " + instance.getName());
            System.out.println("1当前节点: " + instance.getBusinessKey());  // 当前活动节点（如 userTask1）
            System.out.println("2当前节点: " + instance.getActivityId());  // 当前活动节点（如 userTask1）
            System.out.println("3当前节点: " + instance.getBusinessKey());
            System.out.println("3当前节点: " + instance.getBusinessStatus());
        } else {
            System.out.println("流程状态: 已结束或不存在");
        }

        return "查询成功";

    }


}
